import React, { createContext, useContext } from "react";
import useWebSocket from "@/hooks/useWebSocket";

// 创建 WebSocket 上下文
const WebSocketContext = createContext<any>(null);

// WebSocketProvider 组件，用于全局提供 WebSocket 实例和关闭连接的函数
export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
	const { socket, message, sendMessage, close } = useWebSocket();

	return <WebSocketContext.Provider value={{ socket, message, sendMessage, close }}>{children}</WebSocketContext.Provider>;
};

// 自定义钩子，用于在任何组件中获取 WebSocket 实例和关闭连接的函数
export const useWebSocketContext = () => useContext(WebSocketContext);
